package io.github.junxworks.qt.modules.data.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import io.github.junxworks.junx.core.util.DateUtils;
import io.github.junxworks.junx.core.util.StringUtils;
import io.github.junxworks.qt.commons.DateHandleService;
import io.github.junxworks.qt.modules.data.entity.DStockStatMarketIndicator;
import io.github.junxworks.qt.modules.data.mapper.MarketStatMapper;
import io.github.junxworks.qt.modules.data.service.DataStoreService;
import io.github.junxworks.qt.modules.data.service.MarketStatService;
import io.github.junxworks.qt.modules.tushare.TushareConstants;
import io.github.junxworks.qt.modules.tushare.service.TradeInfoService;

@Service("MarketStatService")
public class MarketStatServiceImpl extends DateHandleService implements MarketStatService {
	@Autowired
	private MarketStatMapper statMapper;

	@Autowired
	private DataStoreService dataStoreService;

	@Autowired
	private TradeInfoService tradeInfoService;

	@Override
	public void statMarketIndicatorByDate(String date) {
		statMarketIndicatorByDateAndMarket(date, "主板"); //目前只统计主板
	}

	public void statMarketIndicatorByDateAndMarket(String date, String market) {
		handleDataByDate(date, d -> {
			if (!tradeInfoService.isWeekend(d)) {
				List<DStockStatMarketIndicator> res = statMapper.statMarketIndexClassifyIndicatorsByDate(d, market);
				if (!res.isEmpty()) {
					statMapper.deleteMarketIndicatorDataByDate(d, market);
					dataStoreService.insertBatch(res);
				}
			}
		});
	}

	@Override
	public void statMarketIndicatorByDateRange(String dateRange) {
		handleDataDayByDay(dateRange, 0L, this::statMarketIndicatorByDate);
	}

	/**
	 * 按月来统计
	 *
	 * @param dateRange the date range
	 */
	public void statMoneyFlowByDateRange(String dateRange) {
		handleDataMonthByMonth(dateRange, d -> {
			statMoneyFlowByDate(d);
		});
	}

	/**
	 * 默认统计是上个月最后一个交易日的市值
	 *
	 * @param date the date
	 */
	public void statMoneyFlowByDate(String date) {
		handleDataByDate(date, dd -> {
			Date d = DateUtils.addMonths(DateUtils.parse(dd, TushareConstants.TUSHARE_DATE_FORMAT), -1);
			String lastDay = StringUtils.replace(DateUtils.lastDayOfMonth(d), "-", "");
			String firstDay = StringUtils.replace(DateUtils.firstDayOfMonth(d), "-", "");
			statMapper.deleteMoneyFlowMonthLy(lastDay.substring(0, 6));
			dataStoreService.insertBatch(statMapper.statMoneyFlowByMonth(firstDay, lastDay), 500);
		});
	}

	
}
